package data

import (
	"fmt"
	"geekbang-go-homework/week04/internal/conf"
	"geekbang-go-homework/week04/internal/data/ent"

	"google.golang.org/grpc/grpclog"

	"entgo.io/ent/dialect/sql"

	"entgo.io/ent/dialect"

	_ "github.com/go-sql-driver/mysql"
)

func NewDBClient(conf *conf.Bootstrap, log grpclog.LoggerV2) (*ent.Client, func(), error) {
	dbConf := conf.GetData().GetDatabase()
	if dbConf == nil {
		return nil, nil, nil
	}
	switch dbConf.Driver {
	case dialect.MySQL:
		drv, err := sql.Open(dbConf.Driver, dbConf.Source)
		if err != nil {
			return nil, nil, err
		}
		db := drv.DB()
		db.SetMaxIdleConns(int(dbConf.MaxIdel))
		db.SetMaxOpenConns(int(dbConf.MaxOpen))
		if dbConf.MaxLifetime.IsValid() {
			db.SetConnMaxLifetime(dbConf.MaxLifetime.AsDuration())
		}
		client := ent.NewClient(ent.Driver(ent.NewMyDriver(drv, log)))
		return client, func() {
			if err := client.Close(); err != nil {
				log.Error(err)
			}
		}, nil
	default:
		return nil, nil, fmt.Errorf("unsupported driver: %q", dbConf.Driver)
	}
}
